"""
缓存模块 - 提供数据缓存功能
"""

import os
import json
import pickle
import hashlib
import logging
from typing import Dict, Any, Optional
from datetime import datetime, timedelta

class Cache:
    """数据缓存类"""
    
    def __init__(self, cache_dir: str = None, expire_days: int = 1):
        """
        初始化缓存
        
        参数:
            cache_dir: 缓存目录，默认为~/.fdas/cache
            expire_days: 缓存过期天数，默认为1天
        """
        self.logger = logging.getLogger(self.__class__.__name__)
        
        # 设置缓存目录
        if cache_dir is None:
            home_dir = os.path.expanduser("~")
            cache_dir = os.path.join(home_dir, ".fdas", "cache")
        
        self.cache_dir = cache_dir
        self.expire_days = expire_days
        
        # 创建缓存目录
        os.makedirs(self.cache_dir, exist_ok=True)
        
        self.logger.info(f"缓存目录: {self.cache_dir}")
    
    def _get_cache_path(self, key: str) -> str:
        """
        获取缓存文件路径
        
        参数:
            key: 缓存键
            
        返回:
            缓存文件路径
        """
        # 使用MD5哈希作为文件名
        hash_obj = hashlib.md5(key.encode())
        filename = hash_obj.hexdigest() + ".pickle"
        
        return os.path.join(self.cache_dir, filename)
    
    def get(self, key: str, default: Any = None) -> Any:
        """
        获取缓存数据
        
        参数:
            key: 缓存键
            default: 默认值
            
        返回:
            缓存数据，如果不存在则返回默认值
        """
        cache_path = self._get_cache_path(key)
        
        # 检查缓存文件是否存在
        if not os.path.exists(cache_path):
            return default
        
        try:
            # 读取缓存文件
            with open(cache_path, "rb") as f:
                cache_data = pickle.load(f)
            
            # 检查缓存是否过期
            if "timestamp" in cache_data:
                timestamp = cache_data["timestamp"]
                expire_time = timestamp + timedelta(days=self.expire_days)
                
                if datetime.now() > expire_time:
                    self.logger.debug(f"缓存已过期: {key}")
                    return default
            
            return cache_data.get("data", default)
            
        except Exception as e:
            self.logger.error(f"读取缓存失败: {str(e)}")
            return default
    
    def set(self, key: str, data: Any) -> bool:
        """
        设置缓存数据
        
        参数:
            key: 缓存键
            data: 缓存数据
            
        返回:
            是否成功
        """
        cache_path = self._get_cache_path(key)
        
        try:
            # 写入缓存文件
            cache_data = {
                "timestamp": datetime.now(),
                "data": data
            }
            
            with open(cache_path, "wb") as f:
                pickle.dump(cache_data, f)
            
            return True
            
        except Exception as e:
            self.logger.error(f"写入缓存失败: {str(e)}")
            return False
    
    def delete(self, key: str) -> bool:
        """
        删除缓存数据
        
        参数:
            key: 缓存键
            
        返回:
            是否成功
        """
        cache_path = self._get_cache_path(key)
        
        # 检查缓存文件是否存在
        if not os.path.exists(cache_path):
            return True
        
        try:
            # 删除缓存文件
            os.remove(cache_path)
            return True
            
        except Exception as e:
            self.logger.error(f"删除缓存失败: {str(e)}")
            return False
    
    def clear(self) -> bool:
        """
        清除所有缓存
        
        返回:
            是否成功
        """
        try:
            # 遍历缓存目录
            for filename in os.listdir(self.cache_dir):
                file_path = os.path.join(self.cache_dir, filename)
                
                # 删除文件
                if os.path.isfile(file_path):
                    os.remove(file_path)
            
            self.logger.info("缓存已清除")
            return True
            
        except Exception as e:
            self.logger.error(f"清除缓存失败: {str(e)}")
            return False
    
    def get_stats(self) -> Dict[str, Any]:
        """
        获取缓存统计信息
        
        返回:
            缓存统计信息
        """
        try:
            # 遍历缓存目录
            file_count = 0
            total_size = 0
            
            for filename in os.listdir(self.cache_dir):
                file_path = os.path.join(self.cache_dir, filename)
                
                # 统计文件
                if os.path.isfile(file_path):
                    file_count += 1
                    total_size += os.path.getsize(file_path)
            
            return {
                "file_count": file_count,
                "total_size": total_size,
                "total_size_mb": round(total_size / (1024 * 1024), 2),
                "cache_dir": self.cache_dir
            }
            
        except Exception as e:
            self.logger.error(f"获取缓存统计信息失败: {str(e)}")
            return {
                "error": str(e)
            }